package com.pojocreator.processor;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pojocreator.Utils.CommonUtils;
import com.pojocreator.dto.TableDTO;
import com.sun.codemodel.ClassType;
import com.sun.codemodel.JClassAlreadyExistsException;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;

public class JavaCreatorImpl implements JavaCreator {

	private static final Log log = LogFactory.getLog(JavaCreatorImpl.class);
	
	@Override
	public void createClassFile(TableDTO object, String path) {
		
		if(null!=object){
			//Iterate through each Row and create fields
			Iterator rowIterator = object.getRowToDataTypeMap().entrySet().iterator();

			JCodeModel cm = null;
			try {
				cm = new JCodeModel();
				JDefinedClass dc = cm._class(JMod.PUBLIC,"com."+object.getTableName(),ClassType.CLASS);

				while(rowIterator.hasNext()){
					Map.Entry pairs = (Map.Entry)rowIterator.next();
				
					String varName=pairs.getKey().toString();
					String dataType=pairs.getValue().toString();
					varName=varName.toLowerCase();
					
					Class<?> type=CommonUtils.getEquivalentJavaTypeAsClass(CommonUtils.getEquivalentEnum(dataType));
					
					//Create field
					dc.field(JMod.PRIVATE,type,varName);

					//Create getter
					JMethod m = dc.method(JMod.PUBLIC, type, "get"+CommonUtils.getCamelCasedName(varName));
					m.body()._return(JExpr.refthis(varName));

					//Create Setter
					JMethod m1 = dc.method(JMod.PUBLIC,void.class,"set"+CommonUtils.getCamelCasedName(varName));
					m1.param(String.class, varName);
					m1.body().assign(JExpr.refthis(varName),JExpr.ref(varName));
				}
			} catch (JClassAlreadyExistsException e) {
				log.error("",e);
			}

			File file = new File("./"+path);
			file.mkdirs();
			try {
				cm.build(file);
			} catch (IOException e) {
				log.error("",e);
			}
		} else {
			log.debug("Passed object is NULL");
		}
	}

}
